<template>
	<view>
		<u-navbar :title="form.formKey?'编辑表单':'创建表单'">
		</u-navbar>
		<view class="u-p-20">
			<u-form :model="form" ref="createForm" label-position="top">
				<u-form-item label="表单标题" prop="name" required>
					<u-input v-model="form.name" :border="true" placeholder="请输入表单标题" required />
				</u-form-item>
				<u-form-item label="表单描述" prop="description" required>
					<u-input v-model="form.description" :border="true" type="textarea" :autoHeight="true" height="100"
						placeholder="请输入表单描述" />
				</u-form-item>
			</u-form>
			<u-button @click="submit" type="primary">
				{{form.formKey?'编辑':'创建'}}
			</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					formKey: '',
					name: '',
					description: '',
					type: "1"
				},
				rules: {
					name: [{
						required: true,
						message: '请输入表单标题',
						trigger: 'blur,change'
					}],
					description: [{
						required: true,
						message: '请输入表单描述5个字',
						trigger: 'blur,change'
					}]
				}
			}
		},
		onLoad(options) {
			this.form.formKey = options.formKey
			if (options.formKey) {
				this.$u.api.form.getFormInfo(this.form.formKey).then(data => {
					this.form = data
				})
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		methods: {
			submit() {
				this.$refs.createForm.validate(async valid => {
					if (valid) {
						if (this.form.formKey) {
							await this.$u.api.form.updateForm(this.form)
							this.$u.toast('保存成功')
							uni.redirectTo({
								url: '/pages/form/design/form?formId=' + this.form.formKey
							})
						} else {
							let data = await this.$u.api.form.createForm(this.form)
							this.$u.toast('保存成功')
							uni.redirectTo({
								url: '/pages/form/design/form?formId=' + data.formKey
							})
						}
					} else {
						console.log('xxx')
					}
				});
			}
		},
		onReady() {
			this.$refs.createForm.setRules(this.rules);
		},
	}
</script>

<style lang="scss">

</style>
